import {
  Directive,
  AfterViewInit,
  ElementRef,
  Optional,
  Renderer2,
  HostBinding,
  Input,
  OnInit,
} from '@angular/core';
import { PopoverComponent } from './popover.component';

@Directive({
  selector: '[fuiPopover]',
})
export class PopoverDirective implements AfterViewInit, OnInit {
  @HostBinding('class.fui-popover-open') popoverOpenClass;

  /** Popover component. */
  @Input('fuiPopover') popover: PopoverComponent;

  constructor(
    public elementRef: ElementRef,
    private renderer: Renderer2,
  ) {
  }

  ngOnInit() {
    this.popover.setOverlayOrigin(this);

    this.popover.visible
    .subscribe((visible: boolean) => {
      this.popoverOpenClass = visible;
    });
  }

  ngAfterViewInit() {
    if (this.popover.trigger === 'hover') {
      this.renderer.listen(this.elementRef.nativeElement, 'mouseenter', () => this.show());
      this.renderer.listen(this.elementRef.nativeElement, 'mouseleave', () => this.hide());
    } else if (this.popover.trigger === 'click') {
      this.renderer.listen(this.elementRef.nativeElement, 'click', (e) => {
        e.preventDefault();
        this.show();
      });
    }
  }

  show() {
    this.popover.show();
  }

  hide() {
    this.popover.hide();
  }
}
